﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CSScriptLibrary;


/*
 * Credits for this file:
 * AJ - Jolt (he implemented CS-Script in Jolt)
 */
namespace Blackbird.Utilities.Plugin
{
    /// <summary>
    /// Manages CS-Script plugins.
    /// </summary>
    class PluginManager
    {
        /// <summary>
        /// Dictionary which holds all known scripts.
        /// </summary>
        private Dictionary<string, dynamic> Scripts;

        /// <summary>
        /// Holds information about the directory where scripts are.
        /// </summary>
        private DirectoryInfo ScriptDirectory;

        /// <summary>
        /// The path to the scripts, specified as a string object.
        /// </summary>
        private string ScriptPath;

        /// <summary>
        /// The logging instance of the class.
        /// </summary>
        private Log log;


        /// <summary>
        /// Initialise the class.
        /// </summary>
        /// <param name="ScriptPath">The path where scripts are located.</param>
        

        public PluginManager(string ScriptPath)
        {
            this.ScriptPath = ScriptPath;
            this.ScriptDirectory = new DirectoryInfo(this.ScriptPath);
            this.log = new Log("PluginManager");
        }

        /// <summary>
        /// Initialise the plugins.
        /// </summary>
        public void InitializePlugins()
        {
            log.Debug("Attempting to boot plugins...");
            if (this.ScriptDirectory.Exists)
            {
                foreach (FileInfo FI in this.ScriptDirectory.GetFiles())
                {
                    dynamic ScriptFile; //dynamic so it's determined at runtime -- improve this?

                    try
                    {
                        using (StreamReader Reader = new StreamReader(FI.Open(FileMode.Open)))
                        {
                            ScriptFile = CSScript.LoadCode(Reader.ReadToEnd()).GetStaticMethod();

                            this.Scripts.Add(FI.Name, ScriptFile);


                        }
                    }
                    catch (Exception e)
                    {
                        log.Info(e.Message);
                    }
                }
            }
            else 
            {
                log.Debug("Plugin directory was not found!");
            }

           
        }

    }
}
